<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-item label="小说id" v-bind="validateInfos.bookId" class="bookId-item">
            <a-input v-model:value="formData.bookId" placeholder="请输入小说id" style="width: 100%" :disabled="disabled" @blur="bookIdBlur" />
            <span v-if="isNull" class="bookId-null">该小说不存在！</span>
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item label="作品方向" v-bind="validateInfos.workDirection">
            <j-dict-select-tag
              v-model:value="formData.workDirection"
              dictCode="work_direction"
              placeholder="请选择作品方向"
              :disabled="disabled"
              :showChooseOption="false"
              mode="multiple"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="分类名" v-bind="validateInfos.catId">
            <j-dict-select-tag
              v-model:value="formData.catId"
              dictCode="book_category"
              placeholder="请选择分类名"
              :disabled="disabled"
              :showChooseOption="false"
              mode="multiple"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="有声书封面" v-bind="validateInfos.picUrl" class="picUrl-item">
            <a-input v-model:value="formData.picUrl" placeholder="请输入有声书封面" :disabled="disabled" />
            <div style="height: 112px">
              <j-image-upload v-model:value="formData.picUrl" :disabled="disabled" @change="upPic" />
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="有声书名称" v-bind="validateInfos.bookName">
            <a-input v-model:value="formData.bookName" placeholder="请输入有声书名称" :disabled="disabled" :maxlength="128" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="有声书简介" v-bind="validateInfos.bookDesc">
            <a-input v-model:value="formData.bookDesc" placeholder="请输入有声书简介" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="评分" v-bind="validateInfos.score" class="bookId-item">
            <a-input-number
              v-model:value="formData.score"
              :min="0"
              :max="10"
              step="0.1"
              precision="1"
              placeholder="请输入评分"
              style="width: 100%"
              :disabled="disabled"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="音频状态" v-bind="validateInfos.bookStatus">
            <j-dict-select-tag
              v-model:value="formData.bookStatus"
              dictCode="is_completed"
              :showChooseOption="false"
              placeholder="请选择音频状态"
              :disabled="disabled"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="是否收费" v-bind="validateInfos.isVip">
            <j-dict-select-tag
              v-model:value="formData.isVip"
              dictCode="is_vip"
              :showChooseOption="false"
              placeholder="请选择是否收费"
              :disabled="disabled"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="入库状态" v-bind="validateInfos.status">
            <j-dict-select-tag
              v-model:value="formData.status"
              dictCode="book_status"
              :showChooseOption="false"
              placeholder="请选择入库状态"
              :disabled="disabled"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="语言" v-bind="validateInfos.language">
            <j-dict-select-tag
              v-model:value="formData.language"
              dictCode="language"
              :showChooseOption="false"
              placeholder="请选择语言"
              :disabled="disabled"
              @update:key="languageUpdate"
              ref="languageSelectRef"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="平台" v-bind="validateInfos.platform">
            <j-dict-select-tag
              v-model:value="formData.platform"
              dictCode="platform"
              placeholder="请选择平台"
              :disabled="disabled"
              :showChooseOption="false"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '@/utils/http/axios';
  import { useMessage } from '@/hooks/web/useMessage';
  import JDictSelectTag from '@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '@/utils';
  import { saveOrUpdate } from '../AudioBook.api';
  import { Form } from 'ant-design-vue';
  import JImageUpload from '@/components/Form/src/jeecg/components/JImageUpload.vue';

  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: {
      type: Object,
      default: () => {},
    },
    formBpm: { type: Boolean, default: true },
  });
  const formRef = ref();
  const languageSelectRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    bookId: undefined,
    workDirection: '',
    catId: '',
    picUrl: '',
    bookName: '',
    score: '',
    bookDesc: '',
    bookStatus: '0',
    isVip: '0',
    status: '1',
    language: 'EN',
    platform: '2',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    workDirection: [{ required: true, message: '请输入作品方向!' }],
    catId: [{ required: true, message: '请输入分类名!' }],
    picUrl: [{ required: true, message: '请输入有声书封面!' }],
    bookName: [{ required: true, message: '请输入有声书名称!' }],
    bookDesc: [{ required: true, message: '请输入有声书简介!' }],
    bookStatus: [{ required: true, message: '请输入音频状态!' }],
    isVip: [{ required: true, message: '请输入是否收费!' }],
    status: [{ required: true, message: '请输入入库状态!' }],
    language: [{ required: true, message: '请输入语言!' }],
    score: [{ required: true, message: '请输入评分!' }],
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules);

  // 表单禁用
  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });

  /**
   * 新增
   */
  function add() {
    edit({});
    setTimeout(() => {
      formData.bookStatus = '0';
      formData.isVip = '0';
      formData.status = '1';
    }, 200);
  }

  /**
   * 编辑
   */
  function edit(record) {
    let cloneRecord = JSON.parse(JSON.stringify(record));
    console.log(cloneRecord, 'vvbb');
    isNull.value = false;
    cloneRecord.bookStatus = cloneRecord.bookStatus + '';
    cloneRecord.isVip = cloneRecord.isVip + '';
    cloneRecord.status = cloneRecord.status + '';
    let workDirectionArr = cloneRecord.workDirection.split(',');
    cloneRecord.workDirection = workDirectionArr.map((item) => item + '');
    let catIdArr = cloneRecord.catId.split(',');
    cloneRecord.catId = catIdArr.map((item) => item + '');
    languageUpdate(cloneRecord.language);
    nextTick(() => {
      resetFields();
      //赋值
      Object.assign(formData, cloneRecord);
    });
  }

  const isNull = ref(false);

  /**
   * 小说id获取信息
   */
  async function bookIdBlur() {
    if (!formData.bookId) return;
    let params = {
      id: formData.bookId,
    };
    try {
      // 1262260513468560879
      const data = await defHttp.get({ url: '/novel/book/queryById', params });
      console.log(data);
      isNull.value = false;
      formData.workDirection = data.workDirection > -1 ? [data.workDirection + ''] : '';
      formData.catId = data.catId !== null ? [data.catId + ''] : '';
      formData.picUrl = data.picUrl;
      formData.bookName = data.bookName;
      formData.bookDesc = data.bookDesc;
    } catch (e) {
      isNull.value = true;
    }
  }

  async function upPic(val) {
    formData.posterUrl = val;
  }

  const languageLabel = ref();

  function languageUpdate(val) {
    languageLabel.value = val;
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = JSON.parse(JSON.stringify(formData));
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    // model.language=languageLabel.value
    model.language = languageSelectRef.value.getLable(model.language);
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    min-height: 500px !important;
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }

  .bookId-item {
    /deep/ .ant-form-item-control-input-content {
      position: relative;
    }
  }

  .bookId-null {
    color: #ed6f6f;
    position: absolute;
    bottom: -22px;
    left: 0;
  }

  .picUrl-item {
    .ant-input {
      margin-bottom: 8px;
    }
  }
</style>
